import express from 'express'
import cors from 'cors'
import morgan from 'morgan'
import dotenv from 'dotenv'

import authRoutes from './routes/auth.js'
import studentRoutes from './routes/student.js'
import teacherRoutes from './routes/teacher.js'
import adminRoutes from './routes/admin.js'
import { errorHandler } from './middleware/error.js'
import { testConnection } from './config/database.js'

dotenv.config()

export async function createApp() {
  // 测试数据库连接
  await testConnection()

  const app = express()
  app.use(cors({ origin: true, credentials: true }))
  app.use(express.json())
  app.use(morgan('dev'))

  app.get('/api/health', (_req, res) =>
    res.json({ code: 0, message: 'ok', data: { ts: Date.now() } }),
  )

  app.use('/api/v1/auth', authRoutes)
  app.use('/api/v1/student', studentRoutes)
  app.use('/api/v1/teacher', teacherRoutes)
  app.use('/api/v1/admin', adminRoutes)

  app.use(errorHandler)
  return app
}
